import { LeaveWord } from "@/api/interface/leaveWord";
import { deleteLeaveWordApi, getLeaveWordListApi, updateLeaveWordApi } from "@/api/modules/leaveWord";
import { RootThunkAction, store } from "@/redux";
import { Action } from "@/redux/interface";
import * as types from "@/redux/mutation-types";
import { Dispatch } from "redux";

export const saveLeaveWordList = (leaveWordList: LeaveWord[]) => {
	return {
		type: types.SET_LEAVEWORD_LIST,
		payload: leaveWordList
	};
};

export const getLeaveWordList = (pageNum: number = 1, pageSize: number = 10, wrapper?: Partial<LeaveWord>) => {
	store.dispatch(getList(pageNum, pageSize, wrapper));
};

export const removeLeaveWord = (id: number) => {
	store.dispatch(remove(id));
};

export const updateLeaveWord = (leaveWord: Partial<LeaveWord>, id: number) => {
	store.dispatch(update(leaveWord, id));
};

export const getList = (pageNum: number = 1, pageSize: number = 10, wrapper?: Partial<LeaveWord>): RootThunkAction => {
	return async (dispatch: Dispatch<Action<LeaveWord[]>>) => {
		const res = await getLeaveWordListApi(pageNum, pageSize, wrapper);
		dispatch(saveLeaveWordList(res.data.rows) ?? []);
	};
};

export const remove = (id: number): RootThunkAction => {
	return async dispatch => {
		const res = await deleteLeaveWordApi(id);
		if (res.code === 200) dispatch(getList());
	};
};

export const update = (leaveWord: Partial<LeaveWord>, id: number): RootThunkAction => {
	return async dispatch => {
		const res = await updateLeaveWordApi(leaveWord, id);
		if (res.code === 200) dispatch(getList());
	};
};
